
/**
 * 
 *  V2 版本  可调速风扇 fan_mqtt.c 支持云端、机器人双通道控制
 * 每台互联设备 对应fan_mqtt.c door_mqtt.c  lamb_mqtt.c  water_mqtt.c 编译记得修改 BUILD.gn
 * data:2022.05.30 HelloKun 优化-可调速
 * */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "wifi_connect.h"
#include "MQTTClient.h"

#include "wifiiot_errno.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_adc.h"
#include "wifiiot_uart.h"
#include "wifiiot_pwm.h"
#include "hi_uart.h"

#define UART_BUFF_SIZE 1000
#define MQTT_BUFF_SIZE 1000

static const char *data = "MRobot_fan\r\n";
uint8_t uart_buff[UART_BUFF_SIZE] = {0};
uint8_t *uart_buff_ptr = uart_buff;
char mqtt_buff[MQTT_BUFF_SIZE] = {0};
bool fan_status = false;
static unsigned char sendBuf[1000];
static unsigned char readBuf[1000];

Network network;

void messageArrived(MessageData *data)
{
	printf("Message arrived on topic %.*s: %.*s\n", data->topicName->lenstring.len, data->topicName->lenstring.data,
		   data->message->payloadlen, data->message->payload);
	strcpy(mqtt_buff, data->message->payload);
	printf("mqtt_buff%s \n", mqtt_buff);
}

/************* MRobotUnionDevices Control ******************/
// GPIO 接口与原理图对应  使用哪个就在主函数加入Init、 Ctr函数。

static void MyUartInit(void)
{
	uint32_t ret;
	WifiIotUartAttribute uart_attr = {
		.baudRate = 115200,

		// data_bits: 8bits
		.dataBits = 8,
		.stopBits = 1,
		.parity = 0,
	};

	// Initialize uart driver
	ret = UartInit(WIFI_IOT_UART_IDX_1, &uart_attr, NULL);
	if (ret != WIFI_IOT_SUCCESS)
	{
		printf("Failed to init uart! Err code = %d\n", ret);
		return;
	}
}

/**********************Fan**************************/
static void FanInit(void)
{
	//初始化GPIO
	GpioInit();
	IoSetFunc(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_IO_FUNC_GPIO_9_PWM0_OUT);
	GpioSetDir(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_GPIO_DIR_OUT);
	PwmInit(WIFI_IOT_PWM_PORT_PWM0);
	PwmStart(WIFI_IOT_PWM_PORT_PWM0, 40000, 40000); //duty 0-65535  freq  160M/0-65535
	GpioInit();
	IoSetFunc(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_IO_FUNC_GPIO_2_PWM2_OUT);
	GpioSetDir(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_GPIO_DIR_OUT);
	PwmInit(WIFI_IOT_PWM_PORT_PWM2); //测试接口  bearpi 板载led
}
static void FanCtr(void)
{
	//通过串口1接收MRobot2Fan data
	//UartRead(WIFI_IOT_UART_IDX_1, uart_buff_ptr, UART_BUFF_SIZE); // 修改timeout读取/vendor/hisi/hi3861/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_wifiiot_uart.c
	hi_uart_read_timeout(WIFI_IOT_UART_IDX_1, uart_buff_ptr, UART_BUFF_SIZE, 10);
	printf("Uart1 read fan data:%s\n", uart_buff_ptr);
	if ((uart_buff[0] == '1' && uart_buff[1] == '0') || (mqtt_buff[0] == '1' && mqtt_buff[1] == '0'))
	{
		printf("******* Fan Off *****\n");
		PwmStop(WIFI_IOT_PWM_PORT_PWM0); //关闭
		PwmStop(WIFI_IOT_PWM_PORT_PWM2); //关闭
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		fan_status = false;
		return;
	}
	if ((uart_buff[0] == '1' && uart_buff[1] == '1') || (mqtt_buff[0] == '1' && mqtt_buff[1] == '1'))
	{
		printf("******* Fan ON lev-1*****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM0, 15000, 40000); //duty 0-65535  freq  160M/0-65535
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 15000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		fan_status = true;
		return;
	}
	if ((uart_buff[0] == '1' && uart_buff[1] == '2') || (mqtt_buff[0] == '1' && mqtt_buff[1] == '2'))
	{
		printf("******* Fan ON lev-2*****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM0, 25000, 40000); //duty 0-65535  freq  160M/0-65535
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 25000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		fan_status = true;
		return;
	}
	if ((uart_buff[0] == '1' && uart_buff[1] == '3') || (mqtt_buff[0] == '1' && mqtt_buff[1] == '3'))
	{
		printf("******* Fan ON lev-3 *****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM0, 40000, 40000); //duty 0-65535  freq  160M/0-65535
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 40000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		fan_status = true;
	}

	// // mqtt
	// if (mqtt_buff[0] == '1' && mqtt_buff[1] == '0')
	// {
	// 	printf("******* 风扇 关 *****\n");
	// 	PwmStop(WIFI_IOT_PWM_PORT_PWM1); //关闭
	// 	PwmStop(WIFI_IOT_PWM_PORT_PWM2); //关闭
	// }
	// if (mqtt_buff[0] == '1' && mqtt_buff[1] == '1')
	// {
	// 	printf("******* 风扇 开 *****\n");
	// 	PwmStart(WIFI_IOT_PWM_PORT_PWM1, 50000, 40000);
	// 	PwmStart(WIFI_IOT_PWM_PORT_PWM2, 50000, 40000);
	// }
}

static void MQTT_FanTask(void)
{
	MyUartInit();
	FanInit();

	WifiConnect("r1", "88888889");
	printf("Starting ...\n");
	int rc, count = 0;
	MQTTClient client;

	NetworkInit(&network);
	printf("NetworkConnect  ...\n");

begin:
	NetworkConnect(&network, "120.55.170.12", 1883); // hellokun.cn
	printf("MQTTClientInit  ...\n");
	MQTTClientInit(&client, &network, 2000, sendBuf, sizeof(sendBuf), readBuf, sizeof(readBuf));

	MQTTString clientId = MQTTString_initializer;
	clientId.cstring = "MRobot_fan";

	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	data.clientID = clientId;
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.keepAliveInterval = 0;
	data.cleansession = 1;

	printf("MQTTConnect  ...\n");
	rc = MQTTConnect(&client, &data);
	if (rc != 0)
	{
		printf("MQTTConnect: %d\n", rc);
		NetworkDisconnect(&network);
		MQTTDisconnect(&client);
		osDelay(200);
		goto begin;
	}

	printf("MQTTSubscribe  ...\n");
	//其他设备 web_fan_btn web_door_btn  web_water_btn
	rc = MQTTSubscribe(&client, "web_fan_btn", 2, messageArrived); //回调
	if (rc != 0)
	{
		printf("MQTTSubscribe: %d\n", rc);
		osDelay(200);
		goto begin;
	}

	while (++count)
	{
		//使用哪个设备就在加入对应Init、 Ctr。
		FanCtr(); //串口、mqtt数据控制风扇
		if (fan_status)
		{
			printf("******* Fan ON ********");
		}
		else
		{
			printf("******** Fan Off *********");
		}

		MQTTMessage message;
		char payload[30];

		message.qos = 2;
		message.retained = 0;
		message.payload = payload;
		sprintf(payload, "message number %d", count);
		message.payloadlen = strlen(payload);

		//其他设备 发布door lamb water
		if ((rc = MQTTPublish(&client, "fan", &message)) != 0)
		{
			printf("Return code from MQTT publish is %d\n", rc);
			NetworkDisconnect(&network);
			MQTTDisconnect(&client);
			goto begin;
		}
		osDelay(50);
		printf("----- count = %d ------\r\n", count);
		if (count > 1000)
		{
			count = 1;
		}
	}
}
static void MQTT_Fan(void)
{
	osThreadAttr_t attr;

	attr.name = "MQTT_FanTask";
	attr.attr_bits = 0U;
	attr.cb_mem = NULL;
	attr.cb_size = 0U;
	attr.stack_mem = NULL;
	attr.stack_size = 10240;
	attr.priority = osPriorityNormal;

	if (osThreadNew((osThreadFunc_t)MQTT_FanTask, NULL, &attr) == NULL)
	{
		printf("[MQTT_Fan] Falied to create MQTT_FanTask!\n");
	}
}
APP_FEATURE_INIT(MQTT_Fan);